<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="重要级别" prop="degree">
        <el-input
          v-model="queryParams.degree"
          placeholder="请输入重要级别"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="层级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入层级"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入主题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书籍" prop="bookId" v-show="!lockBookId">
        <el-select
          v-model="queryParams.bookId"
          placeholder="请选择笔记"
          clearable
          size="small"
          @change="getAllChapterList"
        >
          <el-option
            v-for="book in bookOptions"
            :key="book.id"
            :label="book.bookName"
            :value="book.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="章节" prop="chapterId" v-show="!lockChapterId">
        <el-select v-model="queryParams.chapterId" placeholder="请选择章节" clearable size="small">
          <el-option
            v-for="chapter in chapterOptions"
            :key="chapter.id"
            :label="chapter.chapterName"
            :value="chapter.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['note:content:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['note:content:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['note:content:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['note:content:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleCreateQuestion"
        >添加习题</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-lock"
          size="mini"
          v-show="!isLockEdit"
          @click="doLockEdit"
        >锁定界面</el-button>
        <el-tooltip
          class="item"
          effect="dark"
          content="锁定之后，编辑界面不自动隐藏"
          placement="top"
          v-show="isLockEdit"
        >
          <el-tag closable @close="unLockEdit">
            <i class="el-icon-lock"></i>锁定界面
          </el-tag>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="锁定之后，只显示当前所属内容" placement="top">
          <el-tag closable v-show="lockBookId" @close="unLockBook">
            <i class="el-icon-lock"></i>
            锁定：{{lockBookName}}
          </el-tag>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="锁定之后，只显示当前所属内容" placement="top">
          <el-tag closable v-show="lockChapterId" @close="unLockChapter">
            <i class="el-icon-lock"></i>
            锁定：{{lockChapterName}}
          </el-tag>
        </el-tooltip>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="主题" align="center" prop="title" />
      <el-table-column label="书籍" align="center" prop="book.bookName" />
      <el-table-column label="章节" align="center" prop="chapter.chapterName" />
      <el-table-column label="重要级别" align="center" prop="degree" />

      <el-table-column label="层级" align="center" prop="level" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['note:content:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['note:content:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内容对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-row>
        <el-col :span="16">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="主题" prop="title">
              <el-input v-model="form.title" placeholder="请输入主题" />
            </el-form-item>
            <el-form-item label="书籍" prop="bookId" v-show="!lockBookId">
              <el-select
                v-model="form.bookId"
                placeholder="请选择笔记"
                clearable
                size="small"
                @change="getAllChapterListEdit"
              >
                <el-option
                  v-for="book in bookOptions"
                  :key="book.id"
                  :label="book.bookName"
                  :value="book.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="章节" prop="chapterId" v-show="!lockChapterId">
              <el-select v-model="form.chapterId" placeholder="请选择章节" clearable size="small">
                <el-option
                  v-for="chapter in chapterOptionsEdit"
                  :key="chapter.id"
                  :label="chapter.chapterName"
                  :value="chapter.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <editor v-model="form.content" :min-height="192" :uploadUrl="uploadUrl" />
            </el-form-item>
            <el-form-item label="见解" prop="think">
              <editor v-model="form.think" :min-height="192" :uploadUrl="uploadUrl" />
            </el-form-item>
            <el-form-item label="重要级别" prop="degree">
              <el-input v-model="form.degree" placeholder="请输入重要级别" />
            </el-form-item>
            <el-form-item label="层级" prop="level">
              <el-input v-model="form.level" placeholder="请输入层级" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <div style="margin: auto 10%;margin-bottom: 15px;">
            <el-button v-if="form.id" type="primary" @click="toCreateQuestion">创建习题</el-button>
            <el-button type="primary" @click="toPre">上一个</el-button>
            <el-button type="primary" @click="toNext">下一个</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
          <el-form
            :model="dynamicWentryForm"
            ref="dynamicWentryForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item
              v-for="(wentry, index) in dynamicWentryForm.wentrys"
              :label="'词条-' + index"
              :key="wentry.id"
              :prop="'wentrys.' + index + '.value'"
              :rules="{
      required: true, message: '词条不能为空', trigger: 'blur'
    }"
            >
              <el-input v-model="wentry.title"></el-input>
              <el-input type="textarea" :rows="2" v-model="wentry.content"></el-input>
              <el-button
                style="position: absolute;left: -70px;bottom: 0px;"
                @click.prevent="removeWentry(wentry)"
              >删除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="addWentry">新增词条</el-button>
              <el-button @click="resetForm('dynamicWentryForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.id" type="primary" @click="toCreateQuestion">创建习题</el-button>
        <el-button type="primary" @click="toPre">上一个</el-button>
        <el-button type="primary" @click="toNext">下一个</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import {
  listContent,
  getContent,
  delContent,
  addContent,
  updateContent,
  exportContent
} from "@/api/note/content";
import { getAllBook } from "@/api/note/book";
import { getAllChapter } from "@/api/note/chapter";
import Editor from "@/components/Editor";

export default {
  name: "Content",
  components: { Editor },
  data() {
    return {
      isLockEdit: false,
      dynamicWentryForm: {
        wentrys: [
          {
            id: 1,
            title: "",
            content: ""
          }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内容表格数据
      contentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        degree: null,
        level: null,
        title: null,
        bookId: null,
        chapterId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      bookOptions: [],
      chapterOptions: [],
      chapterOptionsEdit: []
    };
  },
  computed: {
    ...mapGetters({
      lockBookId: "bookId",
      lockBookName: "bookName",
      lockChapterId: "chapterId",
      lockChapterName: "chapterName"
    }),
    ...mapState(["refreshBook", "refreshChapter"])
  },
  created() {
    this.getBookList();
    this.getChapter();
    this.getList();
  },
  watch: {
    lockBookId: {
      handler: function(value) {
        this.queryParams.bookId = value;
        this.form.bookId = value;
        this.getList();
        if (value) {
          this.getChapter();
        }
      },
      immediate: true
    },
    lockChapterId: {
      handler: function(value) {
        this.queryParams.chapterId = value;
        this.form.chapterId = value;
        this.getList();
      },
      immediate: true
    },
    refreshBook: {
      handler: function(value) {
        if (value) {
          this.getBookList();
        }
      },
      immediate: true
    },
    refreshChapter: {
      handler: function(value) {
        if (value) {
          this.getChapter();
        }
      },
      immediate: true
    }
  },
  methods: {
    resetWentryForm(formName) {
      this.$refs[formName].resetFields();
    },
    removeWentry(item) {
      var index = this.dynamicWentryForm.wentrys.indexOf(item);
      if (index !== -1) {
        this.dynamicWentryForm.wentrys.splice(index, 1);
      }
    },
    addWentry() {
      this.dynamicWentryForm.wentrys.push({
        content: "",
        title: "",
        id: Date.now()
      });
    },
    getChapter() {
      this.getAllChapterList();
      this.getAllChapterListEdit();
    },
    unLockEdit() {
      this.isLockEdit = false;
    },
    doLockEdit() {
      this.isLockEdit = true;
    },
    unLockBook() {
      this.$store.dispatch("DoSetBook", null);
    },
    unLockChapter() {
      this.$store.dispatch("DoSetChapter", null);
    },
    getBookList() {
      getAllBook().then(response => {
        this.bookOptions = response.rows;
      });
    },
    getAllChapterList() {
      this.queryParams.chapterId = "";
      getAllChapter({ bookId: this.queryParams.bookId }).then(response => {
        this.chapterOptions = response.data;
      });
    },
    getAllChapterListEdit() {
      this.form.chapterId = "";
      getAllChapter({ bookId: this.form.bookId }).then(response => {
        this.chapterOptionsEdit = response.data;
      });
    },
    /** 查询内容列表 */
    getList() {
      if (this.lockBookId) {
        this.queryParams.bookId = this.lockBookId;
      }
      if (this.lockChapterId) {
        this.queryParams.chapterId = this.lockChapterId;
      }

      this.loading = true;
      listContent(this.queryParams).then(response => {
        this.contentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isLockEdit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        createTime: null,
        degree: null,
        level: null,
        think: null,
        title: null,
        userId: null,
        bookId: null,
        chapterId: null
      };
      this.dynamicWentryForm.wentrys = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.getChapter();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getContent(id).then(response => {
        this.form = response.data;
        this.dynamicWentryForm.wentrys = JSON.parse(response.data.wentryJson);
        this.open = true;
        this.title = "修改内容";
      });
    },
    /** 修改按钮操作 */
    handleCreateQuestion() {
      const id = this.ids;
      getContent(id).then(response => {
        this.open = false;
        this.$store.dispatch("DosetContentData", response.data);
        this.$router.push("/note/question");
      });
    },
    toNext() {
      var nextIndex = -1;
      for (let index = 0; index < this.contentList.length; index++) {
        const element = this.contentList[index];
        if (element.id == this.form.id) {
          nextIndex = index + 1;
          break;
        }
      }
      if (nextIndex < 0 || nextIndex == this.contentList.length) {
        this.msgError("没有下一个了");
        return;
      }
      var item = this.contentList[nextIndex];
      this.handleUpdate(item);
    },
    toCreateQuestion() {
      var data = this.form;
      this.open = false;
      this.$store.dispatch("DosetContentData", data);
      this.$router.push("/note/question");
    },
    toPre() {
      var preIndex = -1;
      for (let index = 0; index < this.contentList.length; index++) {
        const element = this.contentList[index];
        if (element.id == this.form.id) {
          preIndex = index - 1;
          break;
        }
      }
      if (preIndex < 0) {
        this.msgError("没有上一个了");
        return;
      }
      var item = this.contentList[preIndex];
      this.handleUpdate(item);
    },
    /** 提交按钮 */
    submitForm() {
      if (this.lockBookId) {
        this.form.bookId = this.lockBookId;
      }
      if (this.lockChapterId) {
        this.form.chapterId = this.lockChapterId;
      }
      this.form.wentryJson = JSON.stringify(this.dynamicWentryForm.wentrys);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContent(this.form).then(response => {
              this.msgSuccess("修改成功");
              if (!this.isLockEdit) {
                this.open = false;
                this.getList();
              }
            });
          } else {
            addContent(this.form).then(response => {
              this.msgSuccess("新增成功");
              if (!this.isLockEdit) {
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除内容编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delContent(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有内容数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportContent(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
